// pages/shopcart/cart/cart.js
const app = getApp()
var help = require('../../../utils/help.js');
var login = require('../../../utils/login.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {

    data: [],
    page: 1, // 当前页
    is_load: true, // 是否继续加载
    load_lock: false, // 加载锁
    load_ts: '',
    keyword: '',
    total: 0,
    checkall: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loadData(true);
  },

  /**
   * 加载数据
   */
  loadData: function (is_one) {
    var that = this;

    if (is_one === true) {
      that.setData({
        is_load: true
      })
    }
    if (this.data.load_lock || !this.data.is_load) {
      return false;
    }
    this.setData({
      load_lock: true,
      load_ts: '正在加载'
    })
    if (is_one === true) {
      that.setData({
        page: 1,
        data: []
      })
    }

    var url = app.data.apiUrl + 'Goods/listCart';
    var data = {
      token: app.data.userInfo ? app.data.userInfo.token : '',
      keyword: that.data.keyword,
      page: that.data.page,
    };
    help.get(url, data, that, function (res, that) {
      that.setData({
        load_lock: false
      })
      var result = res.data;
      console.log(result);
      if (result.code == 1) {
        if (result.data.length > 0) {
          if (is_one === true) {
            var new_data = result.data;
          } else {
            var new_data = that.data.data.concat(result.data)
          }
          console.log(new_data)
          that.setData({
            data: new_data,
            checkall: false,
            load_ts: '',
          })
        } else {
          if (is_one === true) {
            that.setData({
              checkall: false,
              data: [],
              checkall: false,
            })
          }
          that.setData({
            checkall: false,
            is_load: false,
            load_ts: '没有更多数据了',

          })
        }
        that.jisuan();
        that.data.page++;

      } else if (result.code == 401) {
        help.msg('登录已失效，正在重新登录...')
        // 重新检测登录状态
        login.getUserInfo(app);
        return false;
      } else {
        help.msg(result.msg)
        return false;
      }

    });
  },

  jian: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var i = 0;
    var showGoodsData = {};
    for (i in that.data.data) {
      if (that.data.data[i].id == id) {
        showGoodsData = that.data.data[i];
        break;
      }
    }
    if (showGoodsData.num > 1) {
      help.get(app.data.apiUrl + 'Goods/addCard', {
        token: app.data.userInfo ? app.data.userInfo.token : '',
        goods_id: showGoodsData.goods_info.id,
        num: showGoodsData.num - 1
      }, that, function (res, that) {
        var result = res.data;
        // console.log(result);
        if (result.code == 1) {
          that.loadData(true)
        } else {
          help.msg(result.msg)
        }

      });
    } else {
      wx.showModal({
        title: '提示',
        content: '确定要删除该商品吗？',
        success: function (res) {
          if (res.confirm) {
            var url = app.data.apiUrl + 'Goods/delCart';
            var data = {
              token: app.data.userInfo ? app.data.userInfo.token : '',
              id: id,
            };
            help.get(url, data, that, function (res, that) {
              var result = res.data;
              console.log(result);
              if (result.code == 1) {
                help.msg(result.msg)
                that.loadData(true);
              } else {
                help.msg(result.msg)
                return false;
              }
            }, function (res, that) {
              wx.hideLoading()
              console.log(res);
              help.msg('网络异常！')
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  jia: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var i = 0;
    var showGoodsData = {};
    for (i in that.data.data) {
      if (that.data.data[i].id == id) {
        showGoodsData = that.data.data[i];
        break;
      }
    }
    if (showGoodsData.num < showGoodsData.goods_info.kucun) {
      help.get(app.data.apiUrl + 'Goods/addCard', {
        token: app.data.userInfo ? app.data.userInfo.token : '',
        goods_id: showGoodsData.goods_info.id,
        num: showGoodsData.num + 1
      }, that, function (res, that) {
        var result = res.data;
        // console.log(result);
        if (result.code == 1) {
          that.loadData(true)
        } else {
          help.msg(result.msg)
        }

      });
    }
  },
  set_num: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var i = 0;
    var showGoodsData = {};
    for (i in that.data.data) {
      if (that.data.data[i].id == id) {
        showGoodsData = that.data.data[i];
        break;
      }
    }
    var num = e.detail.value;
    if (num <= 0 && num !== '') {
      wx.showModal({
        title: '提示',
        content: '确定要删除该商品吗？',
        success: function (res) {
          if (res.confirm) {
            var url = app.data.apiUrl + 'Goods/delCart';
            var data = {
              token: app.data.userInfo ? app.data.userInfo.token : '',
              id: id,
            };
            help.get(url, data, that, function (res, that) {
              var result = res.data;
              console.log(result);
              if (result.code == 1) {
                help.msg(result.msg)
                that.loadData(true);
              } else {
                help.msg(result.msg)
                return false;
              }
            }, function (res, that) {
              wx.hideLoading()
              console.log(res);
              help.msg('网络异常！')
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else if (num >= showGoodsData.goods_info.kucun) {
      num = showGoodsData.goods_info.kucun;
    }
    if (num > 0 && num !== '') {
      help.get(app.data.apiUrl + 'Goods/addCard', {
        token: app.data.userInfo ? app.data.userInfo.token : '',
        goods_id: showGoodsData.goods_info.id,
        num: num
      }, that, function (res, that) {
        var result = res.data;
        // console.log(result);
        if (result.code == 1) {
          that.loadData(true)
        } else {
          help.msg(result.msg)
        }

      });
    }
    
  },
  sellct: function (e) {
    console.log(e)
    var that = this;
    var id = e.currentTarget.dataset.id;
    var i = 0;
    var showGoodsData = {};
    for (i in that.data.data) {
      if (that.data.data[i].id == id) {
        showGoodsData = that.data.data[i];
        that.data.data[i].checked = !that.data.data[i].checked;
        break;
      }
    }

    that.setData({
      data: that.data.data
    })
    that.jisuan();

  },
  selectall: function (e) {
    var that = this;
    var i = 0;
    var showGoodsData = {};
    for (i in that.data.data) {
      that.data.data[i].checked = !that.data.checkall;
    }
    that.setData({
      data: that.data.data,
      checkall: !that.data.checkall
    })
    that.jisuan();
  },
  // 删除
  del :function(e) {
    var choose_ids = [];
    var that = this;
    var i = 0;
    for (i in that.data.data) {
      if (that.data.data[i].checked == true) {
        choose_ids.push(that.data.data[i].id)
      }
    }
    if (choose_ids.length <= 0) {
      help.msg('请选择删除的商品');
      return false;
    }
    wx.showModal({
      title: '提示',
      content: '确定要删除选择的商品吗？',
      success: function (res) {
        if (res.confirm) {
          var url = app.data.apiUrl + 'Goods/delCart';
          var data = {
            token: app.data.userInfo ? app.data.userInfo.token : '',
            id: choose_ids.join(','),
          };
          help.get(url, data, that, function (res, that) {
            var result = res.data;
            console.log(result);
            if (result.code == 1) {
              help.msg(result.msg)
              that.loadData(true);
            } else {
              help.msg(result.msg)
              return false;
            }
          }, function (res, that) {
            wx.hideLoading()
            console.log(res);
            help.msg('网络异常！')
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 清空
  clear: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定要清空购物车吗？',
      success: function (res) {
        if (res.confirm) {
          var url = app.data.apiUrl + 'Goods/delCartAll';
          var data = {
            token: app.data.userInfo ? app.data.userInfo.token : '',
          };
          help.get(url, data, that, function (res, that) {
            var result = res.data;
            console.log(result);
            if (result.code == 1) {
              help.msg(result.msg)
              that.loadData(true);
            } else {
              help.msg(result.msg)
              return false;
            }
          }, function (res, that) {
            wx.hideLoading()
            console.log(res);
            help.msg('网络异常！')
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  jisuan: function()
  {
    var that = this;
    var total = 0;
    var i = 0;
    for (i in that.data.data) {
      if (that.data.data[i].checked == true) {
        total += parseFloat(that.data.data[i].goods_info.price) * parseInt(that.data.data[i].num);
      }
    }
    that.setData({
      total: total.toFixed(2)
    })
  },

  jiesuan: function()
  {
    var choose_ids = [];
    var that = this;
    var i = 0;
    for (i in that.data.data) {
      if (that.data.data[i].checked == true) {
        choose_ids.push(that.data.data[i].id)
      }
    }
    if (choose_ids.length <= 0) {
      help.msg('请选择结算商品');
      return false;
    }
    help.goUrl('/pages/shopcart/settlement/settlement?cart_ids=' + choose_ids.join(','))
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.loadData(true);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})